package net.zjitc.servlet;



import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/11/22.
 */
@WebServlet(name = "DownloadServlet",urlPatterns = "/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String fileName=request.getParameter("filename");
      //找到文件所在路径，判断要下载的文件是否存在
      /**如果不存在，则响应页面，“你下载的文件不存在”
       * 如果存在，则将文件的内容（流的方式）输出到页面
       *
       * */
      String path=this.getServletContext().getRealPath("/WEB-INF/upload/"+fileName);
        File file=new File(path);
        if(!file.exists()){
          response.setContentType("text/html;charset=utf-8");
          response.getWriter().write("你下载的文件不存在");
          return;
        }

        //1.显示默认的文件名
        //2.客户端打开下载提示框
             // 下载带有中文的文件？？编码方式设置
        fileName=new String(fileName.getBytes("utf-8"),"ISO-8859-1");

        response.addHeader("content-disposition", "attachment;filename=" + fileName);
        //一定以流的方式，否则大小不对
        IOUtils.copy(new FileInputStream(file),response.getOutputStream());

    }
}
